//
//  MakeIce.cpp
//  SnowCone
//
//  Created by luotianqiang1 on 17/3/31.
//
//

#include "MakeIce.h"
#include "MoveHideShade.h"
#include "FrameStatus.h"
#include "particleLayer.h"
#include "LoadingBarAction.h"
#include "BlenderLayer.h"
IMPLEMENT_COCOS2DX_CLASS(MakeIce);
REGIST_SECENE(MakeIce)
bool MakeIce::init(){
    if(BaseStepLayer::init()) {
        _operate = StudioLayer::create("MakeIce.csb");
        addChild(_operate);
        currentWater = nullptr;
        bowl = _operate->getNodeByName("water");
        auto f = FrameStatus::create(bowl->getName());
        f->setSearchAction(_operate->getAction());
        auto rotateF =f->getFrame<cocostudio::timeline::RotationFrame>("pouring0");
        bowlRote = rotateF->getRotation();
        _prompt = _operate->getNodeByName<Sprite*>("finger");
        vector<string> hideNodes = {"mould","water","oven","oven_open","bar_bg"};
        for(auto name:hideNodes)
            _operate->getNodeByName(name)->setVisible(false);
        for(int i=0;i<4;i++){
            auto name = StringUtils::format("water%d",i);
            auto node = _operate->getNodeByName(name);
            if(node != nullptr){
                auto s = dynamic_cast<Sprite*>(node);
                if(s != nullptr) {
                    s->setCascadeOpacityEnabled(false);
                    s->setName("");
                    s->setOpacity(0);
                    auto clip = ClippingNode::create();
                    s->addChild(clip);
                    clip->setAlphaThreshold(0.01f);
                    auto mask = Sprite::createWithSpriteFrame(s->getSpriteFrame());
                    mask->setPosition(s->getContentSize()*.5);
                    clip->setStencil(mask);
                    
                    auto inner = Sprite::createWithSpriteFrame(s->getSpriteFrame());
                    inner->setPosition(s->getContentSize()*.5);
                    clip->addChild(inner);
                    inner->setName(name);
                    inner->setPositionY(-inner->getContentSize().height*.15);
                    inner->setOpacity(0);
                }
            }
        }
        auto particle = _operate->getNodeByName<ParticleSystemQuad*>("particle");
        particle->setPositionType(ParticleSystem::PositionType::FREE);
        particle->stopSystem();
        _operate->getNodeByName<ui::Widget*>("btn")->setEnabled(false);
        
        
        return true;
    }
    return false;
}

void MakeIce::touchEnd(ui::Widget* widget){
    if(widget->getName() == "btn") {
        widget->setTouchEnabled(false);
        _operate->getNodeByName("finger2")->setVisible(false);
        _loopSound = SoundPlayer::getInstance()->playEffectLoop("sound/Freezer running.mp3");
        
        
        stopPrompt();
        auto door = _operate->getNodeByName("oven_close");
        for(int i=1;i<=3;i++){
            auto iceDoor = Sprite::create(StringUtils::format("PNG/3/oven_door%d.png",i));
            iceDoor->setPosition(door->getContentSize()*.5);
            door->addChild(iceDoor);
            iceDoor->setOpacity(0);
            iceDoor->runAction(Sequence::create(DelayTime::create(4.5*(i-1)), FadeIn::create(5.4f),nullptr));
        }
        _operate->getNodeByName("LoadingBar")->runAction(LoadingTo::create(4.5f*3, 100));
        auto mould = _operate->getNodeByName("mouldInOven");
        auto bakeAnimation = Animation::create();
        bakeAnimation->setDelayPerUnit(4.5f);
        for(int i=0;i<3;i++)
            bakeAnimation->addSpriteFrameWithFile(StringUtils::format("PNG/make_2/mould%d.png",i));
        mould->runAction(Sequence::create(Animate::create(bakeAnimation),CallFunc::create([=](){
            this->openDoor();
            ActionHelper::delayFunc(0.5, this, [this](){
                ActionHelper::hide(_operate->getNodeByName("bar_bg"), ActionHelper::ShowDirection::show_from_top);
                auto plate = _operate->getNodeByName("mouldInOven");
                plate->getParent()->reorderChild(plate, 1);
                plate->runAction(Sequence::create(ScaleTo::create(0.9f, 1.5f,1.7f),CallFunc::create([=](){
                    this->addChild(particleLayer::create());
                }),DelayTime::create(1.5),CallFunc::create([](){
                      Director::getInstance()->replaceScene(TransitionPageTurn::create(1.2, BlenderLayer::createScene(), false));
                }), nullptr));
                plate->runAction(JumpTo::create(0.9f, plate->getParent()->getContentSize()*.5f, 200, 1));
                
                
            });
            SoundPlayer::getInstance()->stopEffectLoop(_loopSound);
            _loopSound = -1;
            
        }),nullptr));
    }
}


void MakeIce::onEnterTransitionDidFinish(){
    BaseStepLayer::onEnterTransitionDidFinish();
    Device::setAccelerometerEnabled(true);
    auto mould = _operate->getNodeByName("mould");
    ActionHelper::showBezier(mould, mould->getPosition(), ActionHelper::ShowDirection::show_from_left,nullptr,0.85f);
    mould->setVisible(true);
    mould->setScale(1.15f);
    mould->runAction(ScaleTo::create(0.85f, 1));
    SoundPlayer::getInstance()->playEffect("sound/general/ingredients_fly_in.mp3");
    ActionHelper::delayFunc(0.45f, this, [=](){
        SoundPlayer::getInstance()->playEffect("sound/general/ingredients_fly_in.mp3");
        auto water = _operate->getNodeByName("water");
        auto scale = water->getScale();
        water->setScale(scale*1.2f);
        water->runAction(ScaleTo::create(0.85f, scale));
        ActionHelper::showBezier(water, water->getPosition(), ActionHelper::ShowDirection::show_from_right,[=](){
            auto touchMove = MoveHideShade::create();
            touchMove->setMoveType(MoveComponentType::kTypeBack);
            touchMove->setTarget(LQRect::create(CocosHelper::getNodeRectInWorld(mould)));
            water->addComponent(touchMove);
            ActionHelper::runBezierMoveHideAction(_prompt, _operate->getPosinWord("water"), _operate->getPosinWord("mould"));
            touchMove->addListners(ComponentTouchMove, [=](LQComponent*,OperateListner*){
                if(touchMove->checkInlimit()) {
                    this->stopPrompt();
                    water->removeComponent(touchMove);
                    auto f = FrameStatus::create(water->getName());
                    f->setSearchAction(_operate->getAction());
                    auto pos = f->getFrame<cocostudio::timeline::PositionFrame>("pouring0")->getPosition();
                    auto scale = f->getFrame<cocostudio::timeline::ScaleFrame>("pouring0")->getScaleX();
                    water->runAction(ScaleTo::create(0.3f, scale));
                    water->runAction(Sequence::create(MoveTo::create(0.3f, pos),CallFunc::create([this](){
                        auto incline = _operate->getNodeByName("incline");
                        auto action = RepeatForever::create(Sequence::create(FadeIn::create(0), RotateTo::create(0, 0),RotateTo::create(0.5, -30),DelayTime::create(0.2f), RotateTo::create(0, 0),RotateTo::create(0.5, -30),FadeOut::create(0),DelayTime::create(2.5),nullptr));
                        incline->runAction(action);
                        incline->setVisible(true);
                        
                        
                        auto accle = TouchAccleRoteComponent::create();
                        accle->setEndRote(bowlRote);
                        accle->setBackThreshold(20);
                        accle->setMagnification(120);
                        accle->addListners(ACCLE_ROTE_END, CC_CALLBACK_2(MakeIce::roteEnd, this));
                        accle->addListners(ACCLE_ROTE_BACK, CC_CALLBACK_2(MakeIce::roteBack, this));
                        bowl->addComponent(accle);
                        
                        auto f = FrameStatus::create(bowl->getName());
                        f->setSearchAction(_operate->getAction());
                        vector<Vec2> pos;
                        vector<float> scales;
                        for(int i=0;i<4;i++){
                            pos.push_back(f->getFrame<cocostudio::timeline::PositionFrame>(StringUtils::format("pouring%d",i))->getPosition());
                            scales.push_back(f->getFrame<cocostudio::timeline::ScaleFrame>(StringUtils::format("pouring%d",i))->getScaleX());
                            
                        }
                        f->remove();
                        Vector<cocos2d::FiniteTimeAction *> arrayOfActions;
                        
                        for(int i=0;i<pos.size();i++){
                            if(i==0)
                                arrayOfActions.pushBack(DelayTime::create(0.75f));
                            else
                                arrayOfActions.pushBack(DelayTime::create(0.65f));
                            arrayOfActions.pushBack(CallFunc::create([=](){
                                currentWater = _operate->getNodeByName(StringUtils::format("water%d",i));
                                currentWater->runAction(FadeIn::create(0.7f));
                                currentWater->runAction(MoveTo::create(2.2f, currentWater->getContentSize()*.5));
                                
                            }));
                            arrayOfActions.pushBack(DelayTime::create(2.2f));
                            
                            if(i+1<pos.size())
                                arrayOfActions.pushBack(Spawn::create( MoveTo::create(0.3, pos.at(i+1)),ScaleTo::create(0.3f, scales.at(i+1)), nullptr));
                            
                            
                        }
                        
                        arrayOfActions.pushBack(CallFunc::create([=](){
                            accle->setEnabled(false);
                            currentWater = nullptr;
                            _operate->getNodeByName<ParticleSystemQuad*>("particle")->stopSystem();
                            ActionHelper::delayFunc(0.85, this, [=](){
                                _operate->getNodeByName("pouring")->setVisible(false);
                                ActionHelper::hide(bowl, ActionHelper::ShowDirection::show_from_right);
                                bowl->runAction(RotateTo::create(0.4, 0));
                                bowl = nullptr;
                                showOven();
                            });
                            
                        }));
                        bowl->runAction(Sequence::create(arrayOfActions));
                        _actionManager->pauseTarget(bowl);
                    }), nullptr));
                    
                }
            });
        },0.85f);
        water->setVisible(true);
    });
}

void MakeIce::roteEnd(LQComponent* lc, OperateListner* _lis){
    lc->playSound();
    auto incline = _operate->getNodeByName("incline");
    _operate->getNodeByName("pouring")->setVisible(true);
    incline->stopAllActions();
    incline->setVisible(false);
    lc->getOwner()->setRotation(bowlRote);
    auto particle =
    _operate->getNodeByName<ParticleSystemQuad*>("particle");
    if(!particle->isActive())
        particle->resetSystem();
    _operate->getNodeByName("particle")->setVisible(true);
    
    if(bowl){
        _actionManager->resumeTarget(bowl);
    }
    _actionManager->resumeTarget(_operate->getNodeByName("bowlInner"));
    if(currentWater != nullptr)
        _actionManager->resumeTarget(currentWater);
}

void MakeIce::roteBack(LQComponent* lc, OperateListner* _lis){
    lc->stopSound();
    _operate->getNodeByName("particle")->setVisible(false);
    _operate->getNodeByName("pouring")->setVisible(false);
    auto incline = _operate->getNodeByName("incline");
    incline->stopAllActions();
    incline->setRotation(0);
    ActionHelper::delayFunc(2, incline, [incline](){
        auto action = RepeatForever::create(Sequence::create(FadeIn::create(0), RotateTo::create(0, 0),RotateTo::create(0.5, -30),DelayTime::create(0.2f), RotateTo::create(0, 0),RotateTo::create(0.5, -30),FadeOut::create(0),DelayTime::create(2.5),nullptr));
        incline->runAction(action);
        incline->setVisible(true);
    });
    if(bowl){
        _actionManager->pauseTarget(bowl);
        
    }
    if(currentWater != nullptr)
        _actionManager->pauseTarget(currentWater);
}

void MakeIce::openDoor(){
    auto oven_close = _operate->getNodeByName("oven_close");
    float time0 = 0.4;
    float time1 = 0.1;
    auto openCloseNode = Sequence::create(EaseExponentialIn::create(ScaleTo::create(time0, 1,0.23)),Hide::create(), nullptr);
    oven_close->runAction(openCloseNode);
    
    auto oven_open = _operate->getNodeByName("oven_open");
    oven_open->setScale(1, -0.61);
    auto openOpeneNode = Sequence::create(DelayTime::create(time0),Show::create(),ScaleTo::create(time1, 1), nullptr);
    oven_open->runAction(openOpeneNode);
    
    SoundPlayer::getInstance()->playEffect("sound/oven_open.mp3");
}

void MakeIce::showOven(){
    auto oven = _operate->getNodeByName("oven");
    SoundPlayer::getInstance()->playEffect("sound/general/ingredients_fly_in.mp3");
    ActionHelper::showBezier(oven, oven->getPosition(), ActionHelper::ShowDirection::show_from_right,[=](){
        auto shadow = Sprite::createWithSpriteFrameName("PNG/3/oven_.png");
        shadow->setOpacity(0);
        shadow->setPosition(oven->getContentSize()*.5);
        oven->addChild(shadow,-1);
        shadow->runAction(FadeIn::create(0.2f));
        openDoor();
        
        ActionHelper::delayFunc(0.5f, this, [this](){
            auto mould = _operate->getNodeByName("mould");
            auto move = TouchMoveComponent::create();
            move->setMoveType(MoveComponentType::kTypeBack);
            move->setTarget(LQRect::create(CocosHelper::getNodeRectInWorld(_operate->getNodeByName("limit"))));
            mould->addComponent(move);
            move->addListners(ComponentTouchEnd,[this](LQComponent* lc,OperateListner*){
                lc->setEnabled(false);
                this->stopPrompt();
                
                auto f = FrameStatus::create(lc->getOwner()->getName());
                f->setSearchAction(_operate->getAction());
                auto moudleScale = f->getFrame<cocostudio::timeline::ScaleFrame>("moveEnd");
                lc->getOwner()->runAction(ScaleTo::create(0.7f, moudleScale->getScaleX(),moudleScale->getScaleY()));
                lc->getOwner()->runAction(Sequence::create(JumpTo::create(0.7f, f->getFrame<cocostudio::timeline::PositionFrame>("moveEnd")->getPosition(), 150, 1),CallFunc::create([=](){
                    
                    
                    SoundPlayer::getInstance()->playEffect("sound/oven_closedoor.mp3");
                    
                    auto oven_close = _operate->getNodeByName("oven_close");
                    float time0 = 0.4;
                    float time1 = 0.1;
                    oven_close->setScale(1,0.23);
                    auto coloseCloseNode = Sequence::create(DelayTime::create(time0),Show::create(),ScaleTo::create(time1, 1),CallFunc::create([=](){
                        lc->getOwner()->removeFromParent();
                        _operate->getNodeByName("mouldInOven")->setVisible(true);
                        
                        auto table = _operate->getNodeByName("table");
                        auto tableF= FrameStatus::create(table->getName());
                        tableF->setSearchAction(_operate->getAction());
                        auto tablePos = tableF->getFrame<cocostudio::timeline::PositionFrame>("oven")->getPosition();
                        table->runAction(JumpTo::create(0.8f, tablePos, 100, 1));
                        table->runAction(ScaleTo::create(0.8f, tableF->getFrame<cocostudio::timeline::ScaleFrame>("oven")->getScaleY()));
                        
                        auto bg = _operate->getNodeByName("bg");
                        auto bgF = FrameStatus::create(bg->getName());
                        bgF->setSearchAction(_operate->getAction());
                        bg->runAction(bgF->createAction(0.8f, "oven"));
                        
                        auto oven = _operate->getNodeByName("oven");
                        auto ovenF= FrameStatus::create(oven->getName());
                        ovenF->setSearchAction(_operate->getAction());
                        auto ovenPos = ovenF->getFrame<cocostudio::timeline::PositionFrame>("oven")->getPosition();
                        oven->runAction(JumpTo::create(0.8f, ovenPos, 150, 1));
                        oven->runAction(Sequence::create(ScaleTo::create(0.8f, ovenF->getFrame<cocostudio::timeline::ScaleFrame>("oven")->getScaleY()),CallFunc::create([this](){
                            auto bar_bg = _operate->getNodeByName("bar_bg");
                            ActionHelper::showBackInOut(bar_bg, bar_bg->getPosition(), ActionHelper::ShowDirection::show_from_top);
                            bar_bg->setVisible(true);
                            auto finger2 = _operate->getNodeByName("finger2");
                            auto btn =  _operate->getNodeByName<ui::Widget*>("btn");
                            finger2->runAction(ActionHelper::createUpDownPrompt());
                            finger2->setVisible(true);
                            btn->setEnabled(true);
                        }) ,nullptr));
                    }), nullptr);
                    oven_close->runAction(coloseCloseNode);
                    
                    auto oven_open = _operate->getNodeByName("oven_open");
                    auto coloseOpeneNode = Sequence::create(EaseExponentialIn::create(ScaleTo::create(time0, 1,-0.61)),Hide::create(), nullptr);
                    oven_open->runAction(coloseOpeneNode);
                }), nullptr));
                f->remove();
            });
            ActionHelper::runBezierMoveHideAction(_prompt, _operate->getPosinWord("mould"), _operate->getPosinWord("limit"));
        });
        
        
    },1);
    oven->setVisible(true);
    
}